package io.github.wanggit.antrpc.console.web.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public abstract class TimeFormatUtil {

    public static final String yyyyMMddHHmm = "yyyy-MM-dd HH:mm";

    /**
     * @param dateStr "2020-05-18T10:21:59.655Z"
     * @return
     */
    public static String tzDateFormat(String dateStr) {
        if (null == dateStr) {
            return null;
        }
        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
            Date date = df.parse(dateStr);
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
        } catch (ParseException e) {
            if (log.isErrorEnabled()) {
                log.error("date format error. " + dateStr);
            }
        }
        return null;
    }

    public static Date checkAndConvert(String dateStr) {
        if (!StringUtils.hasText(dateStr)) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(yyyyMMddHHmm);
        try {
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            if (log.isErrorEnabled()) {
                log.error("date format error. " + dateStr);
            }
        }
        return null;
    }
}
